package com.geen.tuoke.utils.ext

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.geen.tuoke.MyApplication
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseActivity
import com.google.gson.reflect.TypeToken
import com.mylhyl.acp.Acp
import com.mylhyl.acp.AcpListener
import com.mylhyl.acp.AcpOptions
import com.qmuiteam.qmui.skin.QMUISkinManager
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomListSheetBuilder
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import java.util.regex.Matcher
import java.util.regex.Pattern


inline fun <reified T : BaseActivity<*, *>> Activity.startActivity() {
    startActivity(Intent(this, T::class.java))

}

fun dp2px(dpValue: Float): Int {
    return QMUIDisplayHelper.dp2px(MyApplication.instance.applicationContext, dpValue.toInt())
}


inline fun Activity.showMessageDialog(
    message: String,
    title: String = "提示",
    yesActionStr: String = "是",
    noActionStr: String = "否",
    crossinline yes: () -> Unit,
    crossinline no: () -> Unit
) {
    if (!isFinishing) {


        QMUIDialog.MessageDialogBuilder(this).setTitle(title).setMessage(message)
            .addAction(noActionStr) { dialog, _ ->
                dialog.dismiss()
                no()
            }.addAction(yesActionStr) { dialog, _ ->
                dialog.dismiss()
                yes()
            }.show()

    }
}

inline fun Activity.showMessageDialog(
    title: String,
    message: String,
    yesActionStr: String = "确定",
    noActionStr: String = "取消",
    crossinline yes: () -> Unit
) {
    if (!isFinishing) {

        QMUIDialog.MessageDialogBuilder(this).setTitle(title).setMessage(message)
            .addAction(noActionStr) { dialog, _ ->
                dialog.dismiss()

            }.addAction(yesActionStr) { dialog, _ ->
                dialog.dismiss()
                yes()
            }.show()

    }
}

inline fun <reified T> genericType() = object : TypeToken<T>() {}.type

fun isIntMultiple(receiveNum: Double, packageUnitNum: Double): Boolean {
    if (packageUnitNum == 0.0) {
        return true
    }
    return (receiveNum * 10000) % (packageUnitNum * 10000) == 0.0
}

fun FragmentActivity.disMissDialogFragment(fragmentTag: String) {
    val prev: Fragment? = supportFragmentManager.findFragmentByTag(fragmentTag)
    if (prev != null) {
        val df: DialogFragment = prev as DialogFragment
        df.dismiss()
    }
}

/***
 * 判断是否是整型
 * @param str String?
 * @return Boolean
 */
fun isNumeric(str: String): Boolean {
    val tNumber = "[0-9]*"
    val pattern: Pattern = Pattern.compile(tNumber)
    val isNum: Matcher = pattern.matcher(str)
    return isNum.matches()
}

/***
 * 判断是否是数学类型
 * @param s String
 * @return Boolean
 */
fun isMathNumber(s: String): Boolean { //合法数字返回true
    //这个正则表达式能够过滤0.0.0、8-99这种不合法的数字
    val reg = "^[-\\\\+]?([0-9]+\\\\.?)?[0-9]+$"
    val pattern: Pattern = Pattern.compile(reg)
    val isNum: Matcher = pattern.matcher(s)
    return isNum.matches()
}

/***
 * 检查指定权限
 */
fun checkAppPermission(permission: String, callBack: () -> Unit){
    Acp.getInstance(MyApplication.instance).request(
        AcpOptions.Builder()
            .setPermissions(
                permission
            ).setDeniedMessage("您拒绝了相关使用权限，app功能将无法正常使用，请去权限授权")
            .build(),
        object : AcpListener {
            override fun onGranted() {
                callBack()
            }

            override fun onDenied(permissions: List<String>) {

            }
        })
}

/***
 * 检查app 所需要的权限
 * @param callBack Function0<Unit>
 */
fun checkAppPermission(callBack: () -> Unit){
    Acp.getInstance(MyApplication.instance).request(
        AcpOptions.Builder()
            .setPermissions(
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ).setDeniedMessage("您拒绝了相关使用权限，app功能将无法正常使用，请去权限授权")
            .build(),
        object : AcpListener {
            override fun onGranted() {
                callBack()
            }

            override fun onDenied(permissions: List<String>) {

            }
        })
}

inline fun Activity.showBottomSheetList(
    gravityCenter: Boolean = true,
    addCancelBtn: Boolean = false,
    withIcon: Boolean = false,
    title: CharSequence = "",
    itemList: List<String>,
    allowDragDismiss: Boolean = true,
    withMark: Boolean = false
) {
    val builder = BottomListSheetBuilder(this)
    builder.setGravityCenter(gravityCenter)
        .setSkinManager(QMUISkinManager.defaultInstance(this))
        .setTitle(title)
        .setAddCancelBtn(addCancelBtn)
        .setAllowDrag(allowDragDismiss)
        .setNeedRightMark(withMark)
        .setOnSheetItemClickListener { dialog, itemView, position, tag ->
            dialog.dismiss()
        }
    if (withMark) {
        builder.setCheckedIndex(40)
    }
    for (i in 1..itemList.size) {
        if (withIcon) {
            builder.addItem(
                ContextCompat.getDrawable(this, R.mipmap.icon_arrow_right),
                i.toString()
            )
        } else {
            builder.addItem(i.toString())
        }
    }
    builder.build().show()
}

